package com.uam.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.uam.common.constant.Constants;
import com.uam.common.exception.CustomException;
import com.uam.db.mapper.MenuMapper;
import com.uam.db.mapper.UserMapper;
import com.uam.db.model.dto.UserPermissionDto;
import com.uam.db.model.entity.User;
import com.uam.db.model.vo.LoginUser;
import com.uam.web.common.utils.AsyncFactory;
import com.uam.web.common.utils.AsyncManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author GoryLee
 * @Date 2022/12/5 01:51
 * @Version 1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;


    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        // 查询用户认证信息
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
                .eq(User::getLoginName, loginName);
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginName, "", Constants.FAIL, Constants.LOGIN_TITLE, Constants.LOGIN_MSG_ERROR));
            throw new CustomException("用户名或者密码错误");
        }
//        List<String> permissions = ListUtil.toLinkedList("test", "admin");
        List<UserPermissionDto> list = menuMapper.getPermissionsByUserId(user.getUserId());

        Set<String> permissions = new HashSet<>();
        Set<String> urls = new HashSet<>();
        Set<String> roleName = new HashSet<>();
        Set<Long> ids = new HashSet<>();

        if (CollUtil.isNotEmpty(list)) {
            permissions = list.stream().map(UserPermissionDto::getPerms)
                    .collect(Collectors.toSet());
            urls = list.stream().map(UserPermissionDto::getUrl)
                    .collect(Collectors.toSet());
            roleName = list.stream().map(UserPermissionDto::getRoleName)
                    .collect(Collectors.toSet());
            ids = list.stream().map(UserPermissionDto::getMenuId)
                    .collect(Collectors.toSet());

        }
        // 封装UserDetails
        LoginUser loginUser = new LoginUser(user, permissions, urls, roleName,ids);
        return loginUser;
    }

}
